/// 供应商文件模型
/// 
/// 用于表示供应商上传的各类文件信息
class SupplierFileModel {
  /// 文件ID
  final int? id;
  
  /// 项目ID
  final int? projectId;
  
  /// 供应商ID
  final int? supplierId;
  
  /// 文件具体类型标签（由后端返回）：
  /// 1-立项申请与批复资料
  /// 2-招标文件
  /// 3-中标的投标文件（正本）
  /// 4-中标通知书
  /// 5-合同文件
  /// 6-签收单
  /// 7-项目验收申请表
  /// 8-项目验收初验表
  /// 9-项目终验检查表
  /// 0-额外资料
  /// 
  /// ⚠️ 注意：此字段与API请求参数中的fileType（文件类别筛选条件0-6）是不同的概念
  final int? fileType;
  
  /// 文件名称
  final String? fileName;
  
  /// 文件路径/URL
  final String? filePath;
  
  /// 文件大小（字节）
  final int? fileSize;
  
  /// 文件扩展名
  final String? fileExt;
  
  /// 上传时间
  final String? uploadTime;
  
  /// 备注
  final String? remark;
  
  /// 创建时间
  final String? createTime;
  
  SupplierFileModel({
    this.id,
    this.projectId,
    this.supplierId,
    this.fileType,
    this.fileName,
    this.filePath,
    this.fileSize,
    this.fileExt,
    this.uploadTime,
    this.remark,
    this.createTime,
  });
  
  /// 从JSON创建SupplierFileModel实例
  factory SupplierFileModel.fromJson(Map<String, dynamic> json) {
    // 处理时间字段：可能是int时间戳或String
    String? parseTimeField(dynamic value) {
      if (value == null) return null;
      if (value is String) return value;
      if (value is int) {
        // 将时间戳转换为可读的日期时间格式
        try {
          final dateTime = DateTime.fromMillisecondsSinceEpoch(value);
          return '${dateTime.year}-${dateTime.month.toString().padLeft(2, '0')}-${dateTime.day.toString().padLeft(2, '0')} ${dateTime.hour.toString().padLeft(2, '0')}:${dateTime.minute.toString().padLeft(2, '0')}';
        } catch (e) {
          return value.toString();
        }
      }
      return value.toString();
    }
    
    // 从文件名中提取扩展名
    String? extractFileExt(String? fileName) {
      if (fileName == null || fileName.isEmpty) return null;
      final lastDot = fileName.lastIndexOf('.');
      if (lastDot == -1 || lastDot == fileName.length - 1) return null;
      return fileName.substring(lastDot + 1);
    }
    
    final fileName = json['fileName'] as String?;
    final fileExt = json['fileExt'] as String? ?? extractFileExt(fileName);
    
    // 处理fileSize字段：可能是int或String
    int? parseFileSize(dynamic value) {
      if (value == null) return null;
      if (value is int) return value;
      if (value is String) {
        return int.tryParse(value);
      }
      return null;
    }
    
    return SupplierFileModel(
      id: json['id'] as int?,
      projectId: json['projectId'] as int?,
      supplierId: json['supplierId'] as int?,
      fileType: json['fileType'] as int?,
      fileName: fileName,
      filePath: json['filePath'] as String?,
      fileSize: parseFileSize(json['fileSize']),
      fileExt: fileExt,
      uploadTime: parseTimeField(json['uploadTime']),
      remark: json['remark'] as String?,
      createTime: parseTimeField(json['createTime']),
    );
  }
  
  /// 转换为JSON
  Map<String, dynamic> toJson() {
    return {
      'id': id,
      'projectId': projectId,
      'supplierId': supplierId,
      'fileType': fileType,
      'fileName': fileName,
      'filePath': filePath,
      'fileSize': fileSize,
      'fileExt': fileExt,
      'uploadTime': uploadTime,
      'remark': remark,
      'createTime': createTime,
    };
  }
  
  /// 获取文件类型描述
  String get fileTypeDescription {
    switch (fileType) {
      case 1:
        return '立项申请与批复资料';
      case 2:
        return '招标文件';
      case 3:
        return '中标的投标文件（正本）';
      case 4:
        return '中标通知书';
      case 5:
        return '合同文件';
      case 6:
        return '签收单';
      case 7:
        return '项目验收申请表';
      case 8:
        return '项目验收初验表';
      case 9:
        return '项目终验检查表';
      case 0:
        return '额外资料';
      default:
        return '未知类型';
    }
  }
  
  /// 获取文件大小的可读格式
  String get fileSizeReadable {
    if (fileSize == null || fileSize == 0) return '未知大小';
    
    const units = ['B', 'KB', 'MB', 'GB'];
    var size = fileSize!.toDouble();
    var unitIndex = 0;
    
    while (size >= 1024 && unitIndex < units.length - 1) {
      size /= 1024;
      unitIndex++;
    }
    
    return '${size.toStringAsFixed(2)} ${units[unitIndex]}';
  }
  
  /// 获取完整的文件URL
  String getFullFileUrl(String baseUrl) {
    if (filePath == null || filePath!.isEmpty) return '';
    
    // 如果已经是完整URL，直接返回
    if (filePath!.startsWith('http://') || filePath!.startsWith('https://')) {
      return filePath!;
    }
    
    // 否则拼接baseUrl
    var path = filePath!.replaceAll('\\', '/');
    if (!path.startsWith('/')) {
      path = '/$path';
    }
    
    return '$baseUrl$path';
  }
  
  @override
  String toString() {
    return 'SupplierFileModel{id: $id, fileName: $fileName, fileType: $fileType, fileSize: $fileSize}';
  }
}

